package com.lin.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.lin.service.BookServiceImpl;
import com.lin.service.IBookService;
import com.lin.vo.Book;
@WebServlet(name="UpdateBookServlet",urlPatterns={"/updateBookServlet"})
public class UpdateBookServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private IBookService bookService = new BookServiceImpl();
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		// 获取磁盘文件项工厂
		DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
		// 获取解析器
		ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
		// 解析请求
		List<FileItem> fileItemLists;
		Map<String,String> map = new HashMap<>();
		Book book = new Book();
		String fileName =null;
		try {
			 fileItemLists= servletFileUpload.parseRequest(request);
			 // 循环文件项目
			 for(FileItem fileItem : fileItemLists){
				 if(fileItem.isFormField()){
					 String name = fileItem.getFieldName();
					 String value = fileItem.getString("UTF-8");
					 map.put(name, value);
				 }else{
					 // 上传项
					 fileName = fileItem.getName();
					 if(fileItem != null && !"".equals(fileItem)){
						// 说明修改了图片，需要将原来的图片删除
						 String image = map.get("image");
						 image = image.substring(image.indexOf("/")+1);
						// 获取服务器路径
						 String realPath = this.getServletContext().getRealPath("/book_img");
						// 封住成文件对象
						 File file = new File(realPath, fileName);
						// 获取输入流
						InputStream is = fileItem.getInputStream();
						// 获取输出流
						OutputStream os =new FileOutputStream(file);
						int length = 0;
						byte [] buf = new byte[1024];
						while((length = is.read(buf))!=-1){
							os.write(buf, 0, length);
						}
						is.close();
						os.close();
					 }
				 }
			 }
			 // 封装表单数据
			 BeanUtils.populate(book, map);
			 if(fileName != null && !"".equals(fileName)){
				 book.setImage("book_img/"+fileName);
			 }
			 bookService.update(book);
			 request.getRequestDispatcher("/adminBookServlet?method=findAllBook").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
			
	}
}